﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using OilRigSumoWrestlers.Levels;

namespace OilRigSumoWrestlers.Artificial_intelligence
{
    /// <summary>
    /// Contains methods used by the AI
    /// </summary>
    public static class AIHelper
    {
        /// <summary>
        /// Returns whether there is an obstacle between the 
        /// specified positions using Bresenham's algorithm
        /// </summary>
        /// <param name="startPos">The Start position</param>
        /// <param name="endPos">The end position</param>
        /// <param name="level">The level to check against</param>
        static public bool IsPathObstructed(Vector2 startPos, Vector2 endPos, ALevel level)
        {
            float dx = Math.Abs(endPos.X - startPos.X);
            float dy = Math.Abs(endPos.Y - startPos.Y);
            float sx, sy;

            if (startPos.X < endPos.X)
                sx = 1;
            else
                sx = -1;

            if (startPos.Y < endPos.Y)
                sy = 1;
            else
                sy = -1;
            float err = dx - dy;

            //check each tile between the agent and the enemy
            while (true)
            {
                //if obstructing tile is detected
                if (!IsMovableTile(startPos, level))
                    return true;

                if (startPos == endPos)
                    break;
                float e2 = 2 * err;
                if (e2 > -dy)
                {
                    err -= dy;
                    startPos.X += sx;
                }
                if (e2 < dx)
                {
                    err += dx;
                    startPos.Y += sy;
                }
            }

            return false;
        }

        /// <summary>
        /// Returns whether the specified tile is safe to move across
        /// </summary>
        /// <param name="index">The index/position of the tile</param>
        /// <param name="level">The level to check against</param>
        /// <returns></returns>
        static public bool IsMovableTile(Vector2 index, ALevel level)
        {
            switch (level.GetTypeAtPosition(index))
            {
                case GameConstant.LVL_FLOOR:
                    return true;
                case GameConstant.LVL_OIL:
                    return true;
                case GameConstant.LVL_P1:
                    return true;
                case GameConstant.LVL_P2:
                    return true;
                default:
                    return false;
            }
        }
    }
}
